package com.qkl.upload.publics.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;

import java.io.File;
import java.io.IOException;
import java.security.SecureRandom;
import java.text.SimpleDateFormat;
import java.util.Date;

@Slf4j
public class FileHelperUtils {

    private static final String SEP = "/";

    private static SecureRandom RANDOM = new SecureRandom();

    public static String getFileSuffix(String fileName){
        String suffix = "";
        if(StringUtils.isNotEmpty(fileName)){
            int len = fileName.length();
            int lastIndex = fileName.lastIndexOf(".");
            if(lastIndex >= 0 && len > lastIndex){
                suffix = fileName.substring(lastIndex + 1,len);
            }
        }
        return suffix;
    }

    public static  String yyyyMMddPath(){
        return new SimpleDateFormat("yyyyMMdd").format(new Date());
    }

    public static String companyPath(String companyId){
        String defaultPath = "common";
        if(StringUtils.isNotEmpty(companyId)){
            defaultPath = companyId;
        }
        return defaultPath;
    }

    public static String genFilePrefix(){
        long currTime = System.currentTimeMillis();
        int ran = RANDOM.nextInt(10000);
        return String.valueOf(currTime) + ran;
    }

    public static String uploadPath(String companyId,String fileName){
        return companyPath(companyId) + SEP + yyyyMMddPath() + SEP + genFilePrefix() + "." + getFileSuffix(fileName);
    }

    public static void deleteDirectory(String rootDirectory,String subDirectory){
        deleteDirectory(rootDirectory + subDirectory);
    }

    public static void deleteDirectory(String directory){
        if(StringUtils.isEmpty(directory)){
            return;
        }
        File file = new File(directory);
        try{
            FileUtils.deleteDirectory(file);
        }catch (IOException e){
            log.info("====deleteDirectory.directory={},exception={}",directory,e);
        }
    }

    public static void main(String[] args) {
        deleteDirectory("E:\\fiels\\1727530125279350785000");
    }

}
